package com.jiexin.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Statement;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 文件操作工具类
 * @author Booker
 */
@Slf4j
public final class FileUtil {

	public static String dirPath;

	/**
	 * 删除文件
	 * @param filePath
	 */
	public static void delete(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			file.delete();
		}
	}

	 /**
     * 获取真实文件名（自动去掉文件路径）
     * @param fileName
     * @return
     */
    public static String getRealFileName(String fileName){
       return FilenameUtils.getName(fileName);
    }

    /**
     * 创建文件
     * @param filePath
     * @return
     */
    public static File createFile(String filePath){
        File file;
        try {
            file = new File(filePath);
            File parentDir = file.getParentFile();
            if (!parentDir.exists()){
                FileUtils.forceMkdir(parentDir);
            }
            file.createNewFile();
            return file;
        }catch (Exception e){
            e.printStackTrace();
            log.error( "创建文件失败:{}",e);
        }
        return null;
    }
    /**
     * 复制文件
     * @param source
     * @param target
     * @return
     */
    public static boolean copyFile(String source, String target) {
    	File sourceFile = new File(source);

		if (sourceFile.exists()){
			try(InputStream in = new FileInputStream(sourceFile);
					OutputStream fos = new FileOutputStream(target,false)){
				byte[] buffer = new byte[1024];
				int len;
				while((len = in.read(buffer)) != -1) {
					fos.write(buffer,0,len);
				}
				fos.flush();
			}catch (IOException e) {
				e.printStackTrace();
				log.error("复制文件异常:{}",e);
				return false;
			}
		}
		return true;
    }

	/**
	 *  移动文件到指定目录
	 *  @param  oldPath  String  如：c:/fqf.txt
	 *  @param  newPath  String  如：d:/fqf.txt
	 */
	public static void moveFile(String  oldPath,  String  newPath)  {
		copyFile(oldPath,  newPath);
		delete(oldPath);

	}
	/**
     * 判断某目录是否存在某文件
     * @param path 文件目录
     * @param fileName	文件名
     * @return
     */
    public static boolean isExistFile(String path,String fileName){
    	File dir = new File(path);
    	if (dir.isDirectory()) {
    		String[] list = dir.list();
    		for (String s : list) {
    			if (s.equals(fileName)) {
    				return true;
    			}
    		}
    	}
    	return false;
    }

	/**
	 * 递归检查是否有次文件目录
	 * @param directoryPath 文件目录路径
	 */
	public static File checkFileDirectory(String directoryPath){
		File dir = new File(directoryPath);
		if(!dir.exists()){
			if(!dir.getParentFile().exists()) {
				directoryPath = dir.getParentFile().getPath();
				checkFileDirectory(directoryPath);
			}
			dir.mkdir();
		}
		return dir;
	}


	/**
	 * getMethod.getResponseHeader("Content-Type").getValue()
	 * 根据 URL 和网页类型生成需要保存的网页的文件名，去除 URL 中的非文件名字符
	 */
	private static String getFileNameByUrl(String url, String contentType) {
		//去除 http://
		url = url.substring(7);
		//text/html 类型
		if (contentType.indexOf("html") != -1) {
			url = url.substring(url.lastIndexOf("/")+1);
			return url;
		}
		//如 application/pdf 类型
		else {
			return url.replaceAll("[\\?/:*|<>\"]", "_") + "." +
					contentType.substring(contentType.lastIndexOf("/") + 1);
		}
	}

	/**
	 * 生成目录
	 */
	public static void mkdir(String filePath) {
		if (dirPath == null) {
			dirPath = filePath;
		}
		File fileDir = new File(dirPath);
		if (!fileDir.exists()) {
			fileDir.mkdir();
		}
	}





	/**
	 * 通过网页标题返回网页名称
	 * @param title 标题
	 * @param contentType 网页内容类型
	 * @return 存储的网页名称
	 */
	public static String getFileNameByTitle(String title, String contentType) {
		String filename = "";
		//text/html 类型
		if (contentType.indexOf("html") != -1) {
			filename = title + ".doc";
		}
		return filename;
	}

	/**
	 * 获取顺序文件名
	 * @param index 下标值
	 * @return
	 * @throws Exception
	 */
	public static String getFolderIndex(int index) throws Exception {

		String folderIndex = "";
		if (String.valueOf(index).length() == 2) {
			folderIndex = "0" + String.valueOf(index);
		} else if (String.valueOf(index).length() == 1) {
			folderIndex = "00" + String.valueOf(index);
		} else if (String.valueOf(index).length() >3) {
			throw new Exception("文件数超过3位,请注意");
		}
		return folderIndex;
	}


	/**
	 * 从网络Url中下载文件
	 * @param urlStr 文件的网络地址
	 * @param fileName 文件名称
	 * @param savePath 文件存放路径
	 * @throws IOException
	 */
	public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		//设置超时间为3秒
		conn.setConnectTimeout(3*1000);
		//防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		//得到输入流
		InputStream inputStream = conn.getInputStream();
		//获取自己数组
		byte[] getData = readInputStream(inputStream);
		//文件保存位置
		File saveDir = new File(savePath);
		if(!saveDir.exists()){
			saveDir.mkdir();
		}
		File file = new File(saveDir+File.separator+fileName);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(getData);
		if(fos!=null){
			fos.close();
		}
		if(inputStream!=null){
			inputStream.close();
		}
		log.info("下载附件成功,url:" + urlStr);
	}

	/**
	 * 从输入流中获取字节数组
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static  byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	/**
	 * 最后修改时间大于一分钟的文件
	 * @param srcFiles 源文件
	 * @return 待解析的文件
	 */
    public static File[] getNeedParseFile(File[] srcFiles) {
		List<File> needParseFile = new ArrayList<>(Arrays.asList(srcFiles));
		for (int i = 1; i < needParseFile.size(); i++) {
			long date = needParseFile.get(i).lastModified();
			Date lastModified = new Date(date);
			// (当前时间-最后修改时间)后取其分钟数 < 1则将该文件移除掉,不需要读取并发送中间表
			if (DateUtil.comparedTime(lastModified) < 1) {
				needParseFile.remove(i);
			}
		}
		File[] fileArray = new File[needParseFile.size()];
		return needParseFile.toArray(fileArray);
    }

	/**
	 * 将srcFilePath中的AXML文件解压成agile.xml并放到TempPath文件夹中
	 * @param axmlPath   D:\ACS\axml\ATO000002.AXML 存放axml文件的全路径
	 * @param tempPath   tempPath
	 */
	public static void getXMLFromzip(String axmlPath, String tempPath) throws IOException {
			File agileAxml = new File(axmlPath);
			BufferedOutputStream dest = null;
			FileInputStream fis = new FileInputStream(agileAxml);
			ZipInputStream zis = new ZipInputStream(
					new BufferedInputStream(fis));
			ZipEntry entry;
			while ((entry = zis.getNextEntry()) != null) {
				int count;
				byte data[] = new byte[2048];
				//D:\ACS\temp\用来存放解压出来的agile.xml文件，在程序结束后会将其删除
				FileOutputStream fos = new FileOutputStream(tempPath + "/" + entry.getName());
				dest = new BufferedOutputStream(fos, 2048);
				while ((count = zis.read(data, 0, 2048)) != -1) {
					dest.write(data, 0, count);
				}
				dest.flush();
				dest.close();
			}
			fis.close();
			zis.close();

	}

	/**
	 * 指定文件移到到对应的目录,并删除指定文件
	 * @param currentFile 待移到的文件
	 * @param removeFilePath 移动的文件路径
	 * @param xmlPath xml文件路径
	 */
	public static void removeAXMLFile(String currentFile, String removeFilePath, String xmlPath) {
		FileUtil.copyFile(currentFile, removeFilePath);
		FileUtil.delete(xmlPath);
		FileUtil.delete(currentFile);
	}
}
